﻿using System;
using System.Net;
using System.Text.Encodings.Web;

using Furion;

using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

using Purchasing.Application.Enums;
using Purchasing.EntityFramework.Core;

using Serilog;

using Web.Filters;

namespace Purchasing.Web.Core
{
     
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            //Authorization: Bearer 你的token
            //X - Authorization: Bearer 你的刷新token
            //services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);//开启全局授权

            //// Cookies单独身份验证 采用aop的filter
            //services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            //        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, b =>
            //        {
            //            b.LoginPath = "/Home/Login";
            //        });

            services.AddControllersWithViews()
                .AddRazorRuntimeCompilation()
            .AddJsonOptions(options =>{//处理json转换乱码
              options.JsonSerializerOptions.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;
            })
             .AddInjectWithUnifyResult();

            services.AddMvcCore(config =>
            {
                config.Filters.Add(typeof(MyExceptionFilter));//错误
                config.Filters.Add(new MyActionFilter());//action验证 
                config.Filters.Add(new MyAuthorizationFilter()); //登录或权限
            });

            services.AddDatabaseAccessor(options =>
            {
                options.AddDbPool<DefaultDbContext>();
            });//, "Purchasing.Database.Migrations"

            services.AddSession(options=>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout = TimeSpan.FromMinutes(30);//.FromSeconds(5); //30分钟  确定放弃服务器缓存中的内容前，内容可以空闲多长时间 此属性独立于 Cookie 到期时间。 通过会话中间件传递的每个请求都会重置超时
                options.Cookie.HttpOnly = true;
                // Make the session cookie essential
                options.Cookie.IsEssential = true;
            });

            #region  其他orm
            //// EF orm
            //services.AddDatabaseAccessor(options =>
            //{
            //    // 配置默认数据库
            //    options.AddDbPool<DefaultDbContext>(DbProvider.SqlServer);
            //    /*                options.AddDbPool<FurionDbContext>(DbProvider.Sqlite); // 第一个数据库
            //                    options.AddDbPool<SecondDbContext, SecondDbContextDbContextLocator>(DbProvider.SqlServer);  // 第二个数据库
            //                    options.AddDbPool<ThirdDbContext, ThirdDbContextDbContextLocator>(DbProvider.SqlServer);  // 第三个数据库*/

            //    // 配置多个数据库，多个数据库必须指定数据库上下文定位器
            //    //options.AddDbPool<SqliteDbContext, SqliteDbContextLocaotr>();
            //});

            /* //使用SqlSugar ORM
           services.AddSqlSugar(new ConnectionConfig
           {
               //主库
               ConnectionString = App.Configuration["ConnectionString"],
               DbType = DbType.SqlServer,
               InitKeyType = InitKeyType.Attribute,
               IsAutoCloseConnection = true,
               //从库
               SlaveConnectionConfigs = new List<SlaveConnectionConfig>() {
                                new SlaveConnectionConfig() { HitRate=10, ConnectionString=App.Configuration["ConnectionStringRead"] } ,
                                new SlaveConnectionConfig() { HitRate=10, ConnectionString=App.Configuration["ConnectionStringRead"]  }
                           }
           });*/
            #endregion 

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        { 
            if (env.IsDevelopment())
            {
                Utility.StaticVariables.Aspnetcore_Environment = nameof( EnvironmentEnums.Development);
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseSerilogRequestLogging();    //记录访问日志,添加Furion.Extras.Logging.Serilog包 必须在 UseStaticFiles 和 UseRouting 之间
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseSession();//使用session
            app.UseInject();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}